package com.bolins.examples.subspringside.util;

import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * 生成验证码文字的工具类
 * 
 * @author liuys
 *
 */
public class ChinessText {
	//要生成验证码文字的长度
	private final static int WORD_LENGTH = 4;
	//中文文字编码
	private final static String ENCODE = "GB2312";

	public String getText() throws UnsupportedEncodingException {
		String finalWord = "", firstWord = "";
		int tempInt = 0;
		String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

		Random rand = new Random();

		for (int i = 0; i < WORD_LENGTH; i++) {
			switch (rand.nextInt(3)) {
			case 1:
				tempInt = rand.nextInt(26) + 65;
				firstWord = String.valueOf((char) tempInt);
				break;
			case 2:
				int r1,
				r2,
				r3,
				r4;
				String strH,
				strL;//high&low   
				r1 = rand.nextInt(3) + 11; //前闭后开[11,14)   
				if (r1 == 13) {
					r2 = rand.nextInt(7);
				} else {
					r2 = rand.nextInt(16);
				}

				r3 = rand.nextInt(6) + 10;
				if (r3 == 10) {
					r4 = rand.nextInt(15) + 1;
				} else if (r3 == 15) {
					r4 = rand.nextInt(15);
				} else {
					r4 = rand.nextInt(16);
				}

				strH = array[r1] + array[r2];
				strL = array[r3] + array[r4];

				byte[] bytes = new byte[2];
				bytes[0] = (byte) (Integer.parseInt(strH, 16));
				bytes[1] = (byte) (Integer.parseInt(strL, 16));

				firstWord = new String(bytes, ENCODE);
				break;
			default:
				tempInt = rand.nextInt(10) + 48;
				firstWord = String.valueOf((char) tempInt);
				break;
			}
			finalWord += firstWord;
		}
		return finalWord;
	}

}
